import axios from "axios";
import { message } from "antd";
import { InternalAxiosRequestConfig } from "axios";
import { setToken } from "@/utils";
import { refreshTokenService } from "@/services/login";
import qs from "qs";

const instance = axios.create({
  baseURL: "/api", // 设置请求的基础URL
  timeout: 5000, // 设置请求超时时间
});

const CancelToken = axios.CancelToken;
let cancelMap = new Map();
let isRefreshing = false;
let requestQueue: any[] = []; // 需要重发的请求

function addRequestToQueue(config: InternalAxiosRequestConfig) {
  return new Promise((resolve) => {
    requestQueue.push((token: string) => {
      config.headers.Authorization = `Bearer ${token}`;
      resolve(config);
    });
  });
}

const jumpToLogin = () => {
  cancelMap.forEach((c) => {
    c();
  });
  cancelMap.clear();
  localStorage.clear();
  requestQueue = [];
  window.location.href = "/login";
};

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.paramsSerializer = (params) => {
      //所有请求加上时间戳
      params = Object.assign(
        { ...params },
        { timestamp: new Date().getTime() }
      );
      return qs.stringify(params, {
        arrayFormat: "repeat",
        encode: false,
        skipNulls: true,
        filter(_key, value) {
          // 过滤掉空字符串
          if (value !== "" && value !== null && value !== undefined)
            return value;
        },
      });
    };
    config.headers.Accept = "application/json";
    config.headers["Content-Type"] = "application/json";
    config.headers["Accept-Language"] = "zh-CN";
    config.headers["clientId"] = "lLLPcicWRXRoibZXSENqMbaIw";
    config.headers["deviceToken"] =
      "eyJraWQiOiJKaWFZYWVQaWJMUWM2YTVzaWI0YWlhQ0RtQSIsInR5cCI6IkpXVCIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJ7XCJjbGllbnRJZFwiOlwiRzEzeFZPUnpUaHlCaDRUSTBoUXVpYWdcIixcImRldmljZU1vZGVsXCI6XCIxMjEzMlwiLFwic25cIjpcIjFcIixcImRldmljZUlkXCI6XCJqeUh6VmZseVR3eS1Qb3BKbmhWZVF3XCIsXCJkZXZpY2VOYW1lXCI6XCLlp5rml63nmoR3aW5kb3dzMTAyMjJcIixcInVzZXJJZFwiOlwiMzQ3aWJmOTF0UUJtTk1qVW5sdDdaV2dcIn0iLCJjbGllbnRJZCI6IkcxM3hWT1J6VGh5Qmg0VEkwaFF1aWFnIiwiaW0iOnRydWUsImlzcyI6ImMybW9iaWxlIiwiZGV2aWNlTW9kZWwiOiIxMjEzMiIsInNuIjoiMSIsImV4cCI6MTk4NjAwOTU0NCwiZGV2aWNlSWQiOiJqeUh6VmZseVR3eS1Qb3BKbmhWZVF3IiwiZGV2aWNlTmFtZSI6IuWnmuaXreeahHdpbmRvd3MxMDIyMiIsInVzZXJJZCI6IjM0N2liZjkxdFFCbU5NalVubHQ3WldnIiwiaWF0IjoxNjcwNjQ5NTQ0fQ.keD78Ysgk6IqYbj6ERd2sdtBA_bkvJQa4YjBo4K72nRBp6xghJ3PY-ClmzAjR40tHDISdikq7M8Xed0GGY_E7XvDLbKR_Ra9gg3Hbep2W8Kz74Dqb4YjN71QYrjZBLFrcWMEGFdEKwiXLmMmyah8mKvOd4OxlUKdfXYozIv4HTw";

    const accessToken = localStorage.getItem("token");
    const refreshToken = localStorage.getItem("refresh_token");

    if (config.url.indexOf("noAuth") === -1) {
      if (!accessToken) {
        if (!isRefreshing) {
          isRefreshing = true;
          // 去刷新token
          return refreshTokenService(refreshToken)
            .then((res) => {
              // 设置localstorage
              // setToken(res.token)
              // setAccessToken(res.refreshToken)
              // 执行队列中等待的请求
              requestQueue.forEach((req) => req(res.data.accessToken));
              requestQueue.length = 0; // 清空队列，防止重复执行

              config.headers.Authorization = `Bearer ${res.data.accessToken}`;
              return config;
            })
            .catch((error) => {
              // 处理token续期失败的情况
              jumpToLogin();
            })
            .finally(() => {
              isRefreshing = false;
            });
        }
        // 如果isRefreshing为true，将请求添加到队列中
        return addRequestToQueue(config);
      }
    }
    // 在请求发送前添加请求头
    config.headers["Authorization"] = "Bearer " + localStorage.getItem("token");
    // 添加取消请求的function
    config.customkey = `${config.url}-${new Date().getTime()}`;
    config.cancelToken = new CancelToken(function executor(c) {
      const key = config.customkey;
      cancelMap.set(key, c);
    });

    if (!config.data) config.data = {};
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.status == 200) {
      const key = response.config.customkey;
      const func = cancelMap.get(key);
      func && cancelMap.delete(key);
    }
    // 在响应返回后进行一些额外的处理
    return Promise.resolve(response?.data);
  },
  (error) => {
    if (error.name == "CanceledError") return false;
    const { response } = error;
    const { data } = response;
    const errorObj = {
      data,
      status: response?.status,
      statusText: response?.statusText,
      errorCode: data?.errorCode ?? data?.status ?? data?.error,
      errorMessage: data?.errorMessage ?? data?.error ?? data?.message ?? data,
    };
    let alertMsg = data?.errorMessage ?? data?.message;
    if (data?.messages) {
      alertMsg = (h) => {
        return h(
          "div",
          {},
          data?.messages.map((i) => {
            return h("p", { style: "text-align:left;" }, i);
          })
        );
      };
    }
    message.error(alertMsg || "系统异常");
    if (errorObj.status == 401 || errorObj.status == 403) {
      jumpToLogin();
      return false;
    }
    // 处理一些错误，如网络错误、服务器错误等
    return Promise.reject(error);
  }
);

export default instance;
